<template>
  <div class="app-container">
    <el-row>
      <!-- 树结构 -->
      <el-col :span="6">
        <div class="mainbox-left">
          <div class="box-card">
            <formType name="表单类型" :handle="true" @treeClick="treeClick" />
          </div>
        </div>
      </el-col>
      <el-col :span="18">
        <div class="mainbox">
          <div class="filter-container">
            <el-form v-show="showSearch" ref="queryForm" :model="queryParams"
                     :inline="true" label-width="68px" @submit.native.prevent>
              <el-form-item label="模型名称" prop="formName">
                <el-input
                  v-model.trim="queryParams.formName"
                  placeholder="请输入模型名称"
                  class="filter-item limit"
                  maxlength="30"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="模型编码" prop="formCode">
                <el-input
                  v-model.trim="queryParams.formCode"
                  placeholder="请输入模型编码"
                  class="filter-item limit"
                  maxlength="20"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-form>
            <div class="flex-1" />
            <div>
              <div class="flex-1" />
              <div style="display:flex;">
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
              </div>
            </div>
          </div>
          <div class="table-container table-fullscreen">
            <div class="table-opt-container">
              <el-button
                v-permission="['FORMDESIGN_FORMDESIGN_ADD_BUTTON']"
                type="primary"
                icon="el-icon-plus"
                @click="handleAdd"
              >新增</el-button>
              <div class="flex-1" />
              <dt-dialog-column v-model="isShowTable" :columns="showColumns" :table-ref="$refs.table"
                                @queryTable="getList" />
            </div>
            <el-table
              v-if="isShowTable"
              ref="table"
              v-loading="loading"
              border
              :header-cell-style="{ backgroundColor: '#f2f2f2'}"
              highlight-current-row
              :data="formDesignList"
            >
              <template slot="empty">
                <p>{{ $store.getters.dataText }}</p>
              </template>
              <el-table-column
                fixed="left"
                type="index"
                label="序号"
                width="70"
                :index="(index)=>(queryParams.pageNo - 1) * queryParams.pageSize + index + 1"
              />
              <el-table-column v-if="showColumns[0].show" key="formName" label="模型名称"
                               show-overflow-tooltip align="center" prop="formName" />
              <el-table-column v-if="showColumns[1].show" key="formCode" label="模型编码"
                               show-overflow-tooltip align="center" prop="formCode" />
              <el-table-column v-if="showColumns[2].show" key="categoryName" label="分类"
                               show-overflow-tooltip align="center" prop="categoryName" />
              <el-table-column :key="Math.random()" label="操作" fixed="right"
                               align="center" class-name="small-padding fixed-width" width="400">
                <template slot-scope="scope">
                  <el-button
                    v-permission="['FORMDESIGN_FORMDESIGN_PREVIEW_BUTTON']"
                    size="small"
                    icon="el-icon-edit"
                    @click="handlePreview(scope.row)"
                  >预览</el-button>
                  <el-button
                    v-permission="['FORMDESIGN_FORMDESIGN_DESIGN_BUTTON']"
                    size="small"
                    @click="handleDesign(scope.row)"
                  >设计</el-button>
                  <el-button
                    v-permission="['FORMDESIGN_FORMDESIGN_DROPDOWN_BUTTON']"
                    size="small"
                    @click="handleUpdate(scope.row)"
                  >修改</el-button>
                  <el-button
                    v-permission="['FORMDESIGN_FORMDESIGN_DROPDOWN_BUTTON']"
                    size="small"
                    @click="handleCopy(scope.row)"
                  >复制</el-button>
                  <el-button
                    v-permission="['FORMDESIGN_FORMDESIGN_DROPDOWN_BUTTON']"
                    size="small"
                    type="danger"
                    :disabled="scope.row.currentUserCreated=='N'"
                    @click="handleDelete(scope.row)"
                  >删除</el-button>
                <!-- <el-dropdown style="margin-left: 10px">
                  <el-button
                    v-permission="['FORMDESIGN_FORMDESIGN_DROPDOWN_BUTTON']"
                    :disabled="formDesignList.length<=0"
                    size="small"
                  >更多<i class="el-icon-arrow-down el-icon--right" /></el-button>
                  <el-dropdown-menu slot="dropdown" style="width:80px;text-align:center">
                    <el-dropdown-item
                      @click.native="handleUpdate(scope.row)"
                    >修改</el-dropdown-item>
                    <el-dropdown-item
                      @click.native="handleCopy(scope.row)"
                    >复制</el-dropdown-item>
                    <el-dropdown-item
                      @click.native="handleDelete(scope.row)"
                    >删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown> -->
                </template>
              </el-table-column>
            </el-table>

            <dt-pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNo"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </div>
        </div>
      </el-col>
    </el-row>
    <!-- 添加或修改对话框 -->
    <dt-dialog :title="title[DialogStatus]" :visible.sync="open" @comfirmBtn="submitForm"
               @closeDialog="cancel">
      <div slot="content">
        <el-form ref="form" :model="form" :rules="rules"
                 label-width="82px">
          <el-form-item label="模型名称" prop="formName">
            <el-input v-model.trim="form.formName" placeholder="请输入模型名称" maxlength="30"
                      show-word-limit class="limit" />
          </el-form-item>
          <el-form-item label="模型编码" prop="formCode">
            <el-input v-model.trim="form.formCode" :disabled="DialogStatus=='update'" placeholder="请输入模型编码"
                      maxlength="30" show-word-limit class="limit" />
          </el-form-item>
          <el-form-item label="分类" prop="formType">
            <el-select v-model="form.formType" clearable placeholder="请选择"
                       style="width:670px;">
              <el-option
                v-for="item in categoryList"
                :key="item.categoryId"
                :label="item.categoryName"
                :value="item.categoryId"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </dt-dialog>
    <formDesignPreview ref="formDesignPreviewRef" />
  </div>
</template>

<script>
import { categoryList, listformDesign, getformDesign, editformDesign, copyformDesign, delformDesign, addformDesign } from '@/framework/api/formDesign/formDesign'
import formDesignPreview from './components/formDesignPreview.vue'
import { noChinese } from '@/framework/utils/validate'
import { uuId } from '@/framework/utils/uuid'
import formType from '@/framework/views/workflow/flowManage/flowFormDesign/components/formType.vue'

export default {
  name: 'ApplicationFormDesign',
  dicts: ['formType'],
  components: {
    formDesignPreview, formType
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显隐表格
      isShowTable: true,
      // 选中数组
      ids: [],
      // 列显隐数组
      showColumns: [
        { prop: 'formName', label: '模型名称', show: true },
        { prop: 'formCode', label: '模型编码', show: true },
        { prop: 'categoryName', label: '分类', show: true }
      ],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // personData: '1579401210912616449,1579400603145383938',
      personData: [],
      personDataId: '1579401210912616449,1579400603145383938',
      // 表格数据
      formDesignList: [],
      // 表单类型列表
      categoryList: [],
      DialogStatus: '',
      // 弹出层标题
      title: {
        create: '新增表单',
        update: '修改表单',
        copy: '复制表单'
      },
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        formType: '',
        formCode: null,
        formName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        formName: [
          { required: true, message: '模型名称不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (value.length > 30) {
                callback(new Error('模型名称超长'))
              } else callback()
            }
          }
        ],
        formCode: [
          { required: true, message: '模型编码不能为空', trigger: 'blur' },
          { trigger: 'blur',
            validator: (rule, value, callback) => {
              if (noChinese(value)) {
                callback(new Error('请不要输入中文字符'))
              } else if (value.length > 30) {
                callback(new Error('模型编码超长'))
              } else callback()
            }
          }
        ],
        formType: [
          { required: true, message: '分类不能为空', trigger: 'change' }
        ]
      },
      formType: ''
    }
  },
  created() {
    this.initData()
  },
  methods: {
    treeClick(data) {
      this.orgInfo = data
      this.loading = false
      this.activeName = 'first'
      this.queryParams.formType = data.categoryId
      this.formType = data.categoryId
      this.$nextTick(() => {
        this.getList()
      })
    },
    initData() {
      // this.getList()
      this.getCategoryList()
    },
    // 获取表单类型列表
    getCategoryList() {
      categoryList().then((res) => {
        this.categoryList = res.data
      })
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      listformDesign(this.queryParams).then(({ data: response }) => {
        this.formDesignList = response.rows
        this.total = response.totalRows
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        formType: this.formType,
        formCode: null,
        formName: null,
        formId: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.formId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.form.formCode = uuId(8)
      this.open = true
      // this.title = '添加表单'
      this.DialogStatus = 'create'
      this.getCategoryList()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getCategoryList()
      getformDesign(row.formId).then((response) => {
        this.form = response.data
        this.open = true
        // this.title = '修改表单'
        this.DialogStatus = 'update'
      })
    },
    /** 复制按钮操作 */
    handleCopy(row) {
      this.reset()
      getformDesign(row.formId).then((response) => {
        this.form = response.data
        this.form.formCode = uuId(8)
        this.open = true
        // this.title = '复制表单'
        this.DialogStatus = 'copy'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.formId != null && this.DialogStatus === 'update') {
            editformDesign(this.form).then((response) => {
              this.$dtModal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else if (this.DialogStatus === 'create') {
            addformDesign(this.form).then((response) => {
              this.$dtModal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          } else {
            copyformDesign(this.form).then((response) => {
              this.$dtModal.msgSuccess('复制成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    // // 复制按钮
    // handleCopy(row) {
    //   this.$dtModal.confirm('是否确认复制表单名称为"' + row.formName + '"的数据项？').then(function() {
    //     return copyformDesign(row.formId)
    //   }).then(() => {
    //     this.getList()
    //     this.$dtModal.msgSuccess('复制成功')
    //   }).catch(() => {})
    // },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$dtModal.confirm(`是否确认删除表单名称为"${row.formName}"的数据项？`).then(() => {
        return delformDesign(row.formId)
      }).then(() => {
        this.getList()
        this.$dtModal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    // 预览按钮
    handlePreview(row) {
      if (!row.tableCode) {
        this.$dtModal.msgError('请先进行表单设计！')
        return
      }
      this.$refs.formDesignPreviewRef.handlePreview(row.formContent)
      // this.$refs.formDesignPreviewRef.open = true
    },
    // 设计
    handleDesign(row) {
      this.$router.push({ path: '/design', query: { formId: row.formId, formName: row.formName, tableCode: row.tableCode } })
    }
  }
}
</script>
